<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/classes/payments/paypal.class.php, $Author:  $ */

    class PayPal extends Payment
    {
    	var $aState = array(1 => 'XX', 2 => 'NY', 3 => 'AL', 4 =>'AK', 5 =>'AZ', 6 => 'AR', 7 => 'CA', 8 => 'CO', 9 => 'CT', 10 => 'DE',
                           11 => 'DC', 12 => 'FL', 13 => 'GA', 14 => 'HI', 15 => 'ID', 16 => 'IL', 17 => 'IN', 18 => 'IA', 19 => 'KS',
                           20 => 'KY', 21 => 'LA', 22 => 'ME', 23 => 'MD', 24 => 'MA', 25 => 'MI', 26 => 'MN', 27 => 'MS', 28 => 'MO',
                           29 => 'MT', 30 => 'NE', 31 => 'NV', 32 => 'NH', 33 => 'NJ', 34 => 'NM', 35 => 'NY', 36 => 'NC', 37 => 'ND',
                           38 => 'OH', 39 => 'OK', 40 => 'OR', 41 => 'PA', 42 => 'RI', 43 => 'SC', 44 => 'SD', 45 => 'TN', 46 => 'TX',
                           47 => 'UT', 48 => 'VT', 49 => 'VA', 50 => 'WA', 51 => 'WV', 52 => 'WI', 53 => 'WY', 54 => 'AB', 55 => 'BC',
                           56 => 'MB', 57 => 'NB', 58 => 'NF', 59 => 'NT', 60 => 'NS', 61 => 'NU', 62 => 'ON', 63 => 'PE', 64 => 'PQ',
                           65 => 'SK', 66 => 'YT');
        var $sHttp      = '';
        var $sHost      = '';
        var $sPath      = '';
        var $iPort      = 0;  //callback port
        var $iTimeout   = 30; //in sec
        var $sPostUrl   = '';
    	var $sBusinessMail   = '';
    	var $sReturnUrl = '';
    	var $sCancelUrl = '';
    	var $sNotifUrl  = '';
    	var $sType      = '';
    	var $sEmail     = '';
        var $aCurrency  = array('EUR'=>'&#128;', 'GBP'=>'&#163;', 'JPY'=>'&#165;', 'USD'=>'$');
    	/**
         * Construct
         *
         * @param string $sRecive (Payment recive e.g. User -> Admin or Admin -> User. Default Admin -> User)
         *
         * @return object PayPal
         */
        function PayPal($sRecive = 'admin')
        {
            $this->sHttp        = App::getParam('paypal.http');
            $this->sHost        = App::getParam('paypal.host');
            $this->sPath        = App::getParam('paypal.path');
            $this->iPort        = App::getParam('paypal.port');
            $this->sReturnUrl   = App::makeUrl('subscribe.act_success');
            $this->sCancelUrl   = App::makeUrl('subscribe.act_cancel');
            $this->sNotifUrl    = App::makeUrl('subscribe.act_notify');
            $this->sPostUrl     = $this->sHttp.$this->sHost.$this->sPath;
            $this->sType        = ($sRecive == 'admin') ? 'admin' : 'account';
        }
        /**
         * Make PayPal payment
         *
         * @access public
         * @param integer $iTransactId (unique transaction id e.g. id sale)
         * @param float   $fAmount (amount)
         * @param array   $aAccountInfo (user info)
         *
         * @return array (Hidden Form, Log message)
         */
        function makePayment()
        {
            $aArgs = func_get_args();

            $iTransactId    = intval($aArgs[0][0]);
            $fAmount        = floatval($aArgs[0][1]);
            $aAccountInfo   = $aArgs[0][2];

            switch ($this->sType)
            {
                case 'admin':
                    $this->sEmail       = $aAccountInfo['email'];//Conf::getSetting('ADMIN_PAYPAL_EMAIL_ADDRESS');
                    $this->sBusinessMail = $aAccountInfo['paddress'];
                    break;
                case 'account':
                    $this->sEmail       = $aAccountInfo['email'];
                    $this->sBusinessMail = $aAccountInfo['paddress'];//Conf::getSetting('ADMIN_PAYPAL_EMAIL_ADDRESS');
                    break;
            }
            if (!isset($aAccountInfo['state_id']))
            {
                $aAccountInfo['state_id'] = 0;
            }
            $aAccountInfo['state'] = isset($this->sState[$aAccountInfo['state_id']]) ? $this->sState[$aAccountInfo['state_id']] : '';
            $sForm = $this->_postPayment($iTransactId, $fAmount, $aAccountInfo);
            return (array($sForm,'Transaction: '.$iTransactId.'; Amount: '.$fAmount));
        }

        /**
         * @todo finishPayment. Receive PayPal answer and callback
         *
         * @param array   $data (array with PayPal data)a
         * @param integer $trans_id
          */
        function finishPayment($aResponse)
        {
            $postdata = '';
            foreach($aResponse[0] as $i=>$v)
            {
                $postdata.= $i . '=' . urlencode($v) . '&';
            }
            $postdata.='cmd=_notify-validate';
            $ch=curl_init();
            curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch,CURLOPT_URL, $this->sPostUrl);
            curl_setopt($ch,CURLOPT_POST, 1);
            curl_setopt($ch,CURLOPT_POSTFIELDS, $postdata);
            ob_start();
            curl_exec($ch);
            $response = ob_get_contents();
            $error = curl_error($ch);
            curl_close($ch);
            ob_end_clean();

			$aInfo = $aResponse[0];

			$this->_debug[] = 'Got a response from Paypal';

			if ( $response == 'VERIFIED' )
			{
				$this->_debug[] = 'Payment has been verified';

	            if (isset($aInfo['payment_status']) && $aInfo['payment_status'] == 'Completed')
    	        {
    	        	$this->_debug[] = 'Payment status is set to completed';

        	        $aDetails = array($aInfo['custom'], 'paid');
            	}
            	else
            	{
            		if ( isset($aInfo['txn_type']) )
            		{
            			switch($aInfo['txn_type'])
            			{
            				case 'subscr_cancel':
            				$this->_debug[] = 'Payment has been canceled';

            	  	    	$aDetails = array($aInfo['custom'], 'canceled_gateway');
            	  	    	break;
						}
					}
					else
					{
						$this->_debug[] = 'Default "txn_type"';

						$aDetails = array('', '', '');
					}
				}
			}
			else
			{
				$this->_debug[] = 'Payment was not verfied';

				$aDetails = array('', '', '');
			}

			$this->doDebug();

			return $aDetails;
        }
        /**
         * Make hidden form
         *
         * @access private
         * @param integer $iTransactId
         * @param float   $fAmount
         * @param array   $aAccountInfo
         *
         * @return string (html hidden form)
         */
        function _postPayment($iTransactId, $fAmount, $aAccountInfo)
        {
			$sCurrency=array_key_exists($aAccountInfo['currency'], $this->aCurrency)? $this->aCurrency[$aAccountInfo['currency']] : $aAccountInfo['currency'] ;

			// Build HTML
			$html = '<div class="ajax_message">' . App::format('Mod_Account.order_in_process') . '</div><br />
			<form method="post" name="paypal" action="'.$this->sPostUrl.'">';
			$html .= '<input type="hidden" name="business" value="'.$this->sBusinessMail.'" />';
			$html .= '<input type="hidden" name="item_name" value="Membership '.$aAccountInfo['currency'].' '.$fAmount.' charge (Account: #'.$aAccountInfo['account_id'].', '.$aAccountInfo['user'].')" />';
			$html .= '<input type="hidden" name="item_number" value="'.$iTransactId.'" />';
			$html .= '<input type="hidden" name="currency_code" value="'.$aAccountInfo['currency'].'" />';
			$html .= '
			<input type="hidden" name="return" value="'.$this->sReturnUrl.'">
			<input type="hidden" name="notify_url" value="'.$this->sNotifUrl.'">
            <input type="hidden" name="cancel_return" value="'.$this->sCancelUrl.'">
            <input type="hidden" name="quantity" value="1">
            <input type="hidden" name="invoice" value="'.time().+microtime().'">
			<input type="hidden" name="custom" value="'.$iTransactId.'">
			<input type="hidden" name="state" value="'.$aAccountInfo['state'].'">
			<input type="hidden" name="zip" value="">
            <input type="hidden" NAME="lc" VALUE="US">
            <input type="hidden" NAME="email" VALUE="'.$aAccountInfo['email'].'">
			';
			$html .= '<input type="hidden" name="no_shipping" value="1">';
			$html .= '<input type="hidden" name="no_note" value="1">';

			/* Will be used in the future
			switch ($invoice['recurring_period'])
			{
				case 'M':
					// Recurr monthly
					$t3 = 'M';
					$p3 = 1;
					break;
				case 'Q':
					// Recurr 3 monthly
					$t3 = 'M';
					$p3 = 3;
					break;
				case 'B':
					// Recurr 6 monthly
					$t3 = 'M';
					$p3 = 6;
					break;
				case 'A':
					// Recurr yearly
					$t3 = 'Y';
					$p3 = 1;
					break;
			}
			*/

			// Any recurring payments?
			if ( $aAccountInfo['pay_type'] == 'monthly' )
			{
				$t3 = 'M';
				$p3 = 1;

				$html .= '<input type="hidden" name="cmd" value="_xclick-subscriptions" />';
				$html .= '<input type="hidden" name="a1" value="'.$fAmount.'" />';
				$html .= '<input type="hidden" name="t1" value="'.$t3.'" />';
				$html .= '<input type="hidden" name="p1" value="'.$p3.'" />';
				$html .= '<input type="hidden" name="a3" value="'.$fAmount.'" />';
				$html .= '<input type="hidden" name="t3" value="'.$t3.'" />';
				$html .= '<input type="hidden" name="p3" value="'.$p3.'" />';
				$html .= '<input type="hidden" name="src" value="1">';
				$html .= '<input type="hidden" name="sra" value="1">';
			}
			else
			{
				$html .= '<input type="hidden" name="cmd" value="_xclick" />';
				$html .= '<input type="hidden" name="amount" value="'.$fAmount.'" />';
			}

			$html .= '</form>';
			$html .= '<script type="text/javascript">document.paypal.submit();</script>';
            return $html;
        }
    }
?>